<template>
<div class="project-card" v-loading="loading">
  <div class="project-card-container-top">
    <el-dropdown v-if="btnAuth.createProjectAuth">
      <el-button type="primary" icon="el-icon-plus">{{$t('common.base.create')}}</el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item v-for="(item, index) in projectTypeList" :key="index">
          <div @click="openProjectCreateTab(item.id)">{{ item.label }}</div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <div class="el-dropdown cur-point acenter" @click="handleSelectColumn">
      {{ $t('common.base.choiceCol') }}
      <i class="iconfont icon-fdn-select ml_4"></i>
    </div>
  </div>

  <div class="project-card-list-container">
    <div class="project-card-list" v-for="(status, index) in dataStatusList" :key="index">
      <div class="project-card-list-title">
        <span class="project-card-list-title-name">{{ status.name }}</span>
        <span class="project-card-list-title-count">{{ status.number }}</span>
      </div>

      <div class="project-card-list-content"
        v-if="dataGroup[status.code] && dataGroup[status.code].list.length"
        infinite-scroll-distance="10"
        :infinite-scroll-immediate="false"
        :infinite-scroll-disabled="status.disabled"
        v-infinite-scroll="() => onLoad(status)"
      >
        <div :class="['card-item', status.code == finishCode && 'done']" v-for="(item, index) in dataGroup[status.code].list" :key="index">
          <div class="card-item-container" @click="openProjectViewTab(item)">
            <div class="card-item-top">
              <span>{{ item.projectName }}</span>
              <el-tooltip
                v-if="item.managerList && item.managerList.userId"
                :content="item.managerList.displayName"
                :disabled="!item.managerList.displayName"
                placement="top"
              >
                <img :src="getHead(item.managerList)" />
              </el-tooltip>
            </div>
            <div class="card-item-body">
              <ProjectTaskLabel class="mt_8" :current-row-data="item"/>
              <div class="form-view">
                <div class="form-view-row" v-for="field in fields" :key="field.fieldName">
                  <label>{{ field.displayName }}</label>
                 
                  <div class="form-view-row-content"  @click.stop="openRichtextVisible(item, field)" v-if="field.formType == 'richtext'">
                    <span v-if="item.attributeMap && item.attributeMap[field.fieldName]" class="see-richtext">{{$t('common.base.view')}}</span>
                  </div>
                  <!-- 延期任务 S -->
                  <div class="form-view-row-content" v-else-if="field.fieldName === 'delayedTasks'">
                    {{ renderDelayedTasks(item) }}
                  </div>
                  <!-- 延期任务 E -->
                  <div class="form-view-row-content" v-else>
                    {{ $formatFormField(field, item) }}
                  </div>
                </div>
              </div>
              <el-progress :percentage="item.projectProcess"></el-progress>
            </div>
          </div>
        </div>

        <div class="empty" v-if="status.loading">{{ $t('common.base.loading') }}</div>
        <div class="empty" v-if="!status.loading && status.disabled">{{ $t('common.base.noMoreData') }}</div>
      </div>
    </div>
  </div>
  <!--查看富文本 -->
  <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
</div>
</template>

<script>
/* model */
import { DEFAULT_AVATAR, FINISH_CODE, START_CODE, ViewTypeComponentNameEnum } from '@src/modules/projectManage/projectManageList/model';
/* util */
import _ from 'lodash';
import { renderDelayedTasks } from '@src/modules/projectManage/projectManageList/util/renderProjectTable.js'
/* hooks */
import { useLoading } from '@hooks/useLoading';
import { useOpenTab } from '@src/modules/projectManage/projectManageList/hooks/useOpenTab';
import { useFetchProjectCardList } from '@src/modules/projectManage/projectManageList/hooks/useFetch';
import  {t} from '@src/locales'
/* vue */
import { ref, computed, reactive, onMounted, watch } from 'vue';

import ProjectTaskLabel from '@src/modules/projectManage/components/projectTaskLabel.vue'

export default {
  name: ViewTypeComponentNameEnum.Card,
  props: {
    columns: {
      type: Array,
      default: []
    },
    statusList: {
      type: Array,
      default: []
    },
    params: {
      type: Object,
      default: {}
    },
    btnAuth: {
      type: Object,
      default: {}
    },
    projectTypeList: {
      type: Array,
      default: []
    },
  },
  components: {
    ProjectTaskLabel
  },
  setup(props, { emit }) {
    const { loading, showLoading, hideLoading } = useLoading();
    const { dataGroup, resetDataGroup, fetchProjectCardList } = useFetchProjectCardList();
    const { openProjectCreateTab, openProjectViewTab } = useOpenTab();
    const baseViewRichTextRef = ref(null);
    // 数据状态
    const dataStatusList = ref([]);
    // 完成状态
    const finishCode = ref(FINISH_CODE);
    // 开始状态
    const startCode = ref(START_CODE);
    // 国际化字段
    const global = {
      START: t("common.base.notStart"),
      RUN: t("common.base.processing"),
      COMPLETE: t("common.task.type.finished"),
      CANCEL: t("common.task.materialLackStockState.2"),
    };
    // 显示字段
    const fields = computed(() => props.columns.filter(field => field.show == true).slice(0, 5));

    // 构建搜索参数
    const buildParams = () => {
      return {
        projectStatusId: [],
        projectStatusType: '',
        pageSize: 10,
        pageNum: 1,
      }
    }
    /** 打开富文本弹窗 */
    const openRichtextVisible = (row, column)=> {
      const richtextId = row?.attributeMap?.[column.fieldName]  || ''
      baseViewRichTextRef.value.openDialog(richtextId)
    }
    // 搜索参数
    const searchParams = reactive(buildParams());

    // 搜索
    const search = () => {
      // 重置
      Object.assign(searchParams, buildParams());
      resetDataGroup();

      showLoading();

      const params = { ...props.params, ...searchParams };
      fetchProjectCardList(params).then(() => {
        // 判断各种状态下是否有更多数据
        dataStatusList.value.forEach(status => {
          status.disabled = Boolean(!dataGroup[status.code]?.hasNextPage);
        })
      }).finally(() => {
        hideLoading();
      })
    }

    // 加载
    const onLoad = _.debounce(async (status) => {
      if (status.loading || status.disabled) return;

      status.pageNum++;

      searchParams.pageNum = status.pageNum;
      searchParams.projectStatusId = [status.id];
      searchParams.projectStatusType = status.code;

      status.loading = true;
      status.disabled = true;

      const params = { ...props.params, ...searchParams };
      fetchProjectCardList(params).then(() => {
        status.disabled = Boolean(!dataGroup[status.code]?.hasNextPage);
      }).finally(() => {
        status.loading = false;
      })
    }, 500)

    // 获取头像
    const getHead = (user) => {
      if (user?.head) return user?.head;
      return DEFAULT_AVATAR;
    }

    // 选择列
    const handleSelectColumn = () => {
      emit('handleSelectColumn');
    }

    onMounted(() => {
      search();
    })

    // 监听数据状态
    watch(() => props.statusList, (newValue) => {
      dataStatusList.value = newValue
        .filter(item => item.code)
        .reduce((result, item) => (result.concat(item?.children?.length ? item.children : item)),[])
        .map(item => {
          for (const key in global) {
            if(key === item.code) {
              item.name = global[key]
            }
          }
          return {
            ...item,
            code: item.code || item.id, // 自定义状态只有id
            pageNum: 1, // 各个状态的页码
            loading: false, // 各个状态加载状态
            disabled: true // 是否可以加载
          }
        });
    }, { immediate: true })

    return {
      loading,
      fields,
      dataGroup,
      startCode,
      finishCode,
      dataStatusList,

      search,
      onLoad,
      getHead,
      openProjectViewTab,
      openProjectCreateTab,
      handleSelectColumn,
      openRichtextVisible,
      baseViewRichTextRef,
      renderDelayedTasks
    };
  },
};
</script>

<style lang="scss" scoped>
.project-card {
  height: 100%;
  overflow: hidden;
  .see-richtext {
    color: $color-primary;
    cursor: pointer;
  }
}
.project-card-container-top {
  display: flex;
  justify-content: space-between;
  padding: 8px 15px;
  margin-bottom: 5px;
  border-radius: 4px;
  background-color: #fff;
}

.project-card-list-container {
  width: 100%;
  height: calc(100% - 50px);
  display: flex;
  align-items: flex-start;
  overflow: auto;
 
  .project-card-list {
    width: 296px;
    height: 100%;
    margin: 0 12px;
    flex-shrink: 0;

    &:first-child {
      margin-left: 0;
    }

    &-title {
      height: 32px;
      margin-bottom: 12px;
      display: flex;
      align-items: center;

      &-name {
        font-weight: bold;
        @include text-ellipsis();
      }

      &-count {
        flex: 1;
        margin-left: 8px;
        color: $text-color-regular;
      }

      .el-button {
        margin-left: 8px;
      }
    }

    &-content {
      height: calc(100% - 44px);
      overflow: auto;

      .card-item {
        width: 100%;
        min-height: 230px;
        padding: 16px;
        margin-bottom: 12px;
        background: #fff;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.08);
        border-radius: $button-radius-base;
        cursor: pointer;

        &-container {
          height: 100%;
        }

        &-top {
          display: flex;
          align-items: center;

          span {
            flex: 1;
            font-size: $font-size-large;
            @include text-ellipsis();
          }

          img {
            width: 24px;
            height: 24px;
            border-radius: 100%;
          }
        }

        &-body {
          ::v-deep .form-view {
            height: 156px;
            padding: 8px 0;

            &-row {
              padding: 4px 0;

              label {
                width: 86px;
                margin-right: 4px;
                color: $text-color-secondary;
                @include text-ellipsis();
              }

              &-content {
                @include text-ellipsis();
              }
            }
          }

          ::v-deep .el-progress {
            &-bar {
              padding-right: 60px;
            }
            
            &__text {
              margin-left: 4px;
              color: $text-color-regular;
            }
          }
        }

        &.done {
          .card-item-container {
            opacity: .5;
          }

          .card-item-top span {
            text-decoration: line-through;
          }
        }
      }
    }

    .empty {
      padding: 8px 0 12px;
      font-size: $font-size-small;
      color: $text-color-secondary;
      text-align: center;
    }
  }
}
</style>
